package com.yunyi.web.controller.upload;
import com.yunyi.common.core.domain.AjaxResult;
import io.swagger.annotations.*;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@RestController
@Api(tags = "文件上传接口")
public class FileUploadController {

    // 上传文件的默认存储路径(需要请自行修改)
    private static final String UPLOAD_FOLDER = "C:/Users/Administrator/Desktop/yiyun/yunyi/yunyi-system/src/main/resources/mapper/upload";

    // 允许上传的文件扩展名列表
    private static final List<String> ALLOWED_EXTENSIONS = Arrays.asList("jpg", "png","doc","docx");

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ApiOperation("上传文件")
    public AjaxResult uploadFiles(@ApiParam(value = "要上传的文件", required = true) @RequestPart("files") List<MultipartFile> files) {
        // 遍历处理每个文件
        for (MultipartFile file : files) {
            // 检查文件大小
            if (file.getSize() > 10 * 1024 * 1024) {
                return AjaxResult.error("文件大小超过限制（10MB）。");
            }

            // 检查文件类型
            String fileExtension = getFileExtension(file.getOriginalFilename());
            if (!ALLOWED_EXTENSIONS.contains(fileExtension)) {
                return AjaxResult.error("只允许上传JPG和PNG以及doc格式的图片");
            }

            // 检查总体文件大小
            File uploadDir = new File(UPLOAD_FOLDER);
            long totalSize = 0;
            for (File uploadedFile : uploadDir.listFiles()) {
                totalSize += uploadedFile.length();
            }
            if (totalSize + file.getSize() > 20 * 1024 * 1024) {
                return AjaxResult.error("总文件大小超过限制（20MB）");
            }

            // 保存文件
            if (!file.isEmpty()) {
                try {
                    String fileName = StringUtils.cleanPath(file.getOriginalFilename());
                    File destFile = new File(UPLOAD_FOLDER + File.separator + fileName);
                    file.transferTo(destFile);
                } catch (IOException e) {
                    return AjaxResult.success("文件上传失败");
                }
            } else {
                return AjaxResult.error("文件为空");
            }
        }

        return AjaxResult.success("文件上传成功");
    }


    /**
     * 获取已上传文件的数量
     *
     * @return 已上传文件的数量
     */
    @GetMapping("/fileCount")
    @ApiOperation("获取已上传文件的数量")
    public int getFileCount() {
        File uploadDir = new File(UPLOAD_FOLDER);
        return uploadDir.listFiles().length;
    }

    /**
     * 获取文件的扩展名
     *
     * @param fileName 文件名
     * @return 文件的扩展名
     */
    private String getFileExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex > 0 && dotIndex < fileName.length() - 1) {
            return fileName.substring(dotIndex + 1).toLowerCase();
        } else {
            return "";
        }
    }
}
